// pages/me/userinfo/index.js
const common = require('../../../utils/common.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
    data: {
        userId: '',       //用户ID
        userInfo: [],   //用户信息
        showPopup:false,    //是否显示弹层
        sexArray:['男','女','未知'], //性别
        hidden_nickName:true,
        hidden_brief:true,
        hidden_password:true,
        hidden_phone:true,
        input_val:'',
    },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      var is_login = common.checkLogin(false);
      if (!is_login) return;
      var that = this;
      var token = common.getToken();
      var userId = common.getUserId();
      var data = { token: token, userId: userId };
      var url = `${app.apiHost}centers/index`;     //发而评论接口
      var msg = '加载中';
      var func = function (content) {
          
          that.setData({
              userInfo: content,
              userId: userId,
          });

      };
      var res = common.request(url, data, msg, func, that);
  },
  //修改头像弹窗
  avatar:function(){
      var that=this;
        wx.showActionSheet({
            itemList: ['相册','拍照'],
            success:function(res){
                if (res.tapIndex==0){
                    that.getCamera('album');
                    
                } else if (res.tapIndex == 1){
                    that.getCamera('camera');
                }
            }
        })
  },
  //调用相册/相机
  getCamera: function (type) {     //type:	album 从相册选图，camera 使用相机，
      var that = this;
      var is_login = common.checkLogin(false);
      if (!is_login) return;
      var token = common.getToken();
      var userId = common.getUserId();
      wx.chooseImage({
          count: 1,
          sourceType: [type],
          success: function (res) { 
              var tempPath=res.tempFilePaths[0];
              var upload=wx.uploadFile({
                  url: `${app.apiHost}admincp/upload/index`,    //上传文件接口
                  filePath: tempPath,
                  name: 'file',
                  success:function(res){
                        var imgdata=JSON.parse(res.data);
                        
                        if(imgdata.code==200){
                            let imagePath=imgdata.content.url;
                            let url = `${app.apiHost}centers/uploadImage`;
                            let data = { token: token, userId: userId, imagePath: imagePath };
                            
                            common.request(url, data, '头像更新中', function(content){  //更新头像至数据库
                                let userInfo=that.data.userInfo;
                                userInfo.headUrl=tempPath;
                                that.setData({
                                    userInfo:userInfo,      //更新头像
                                })
                            },that);
                        }else{
                            common.toast('上传失败');
                        }
                  }
              });
              upload.onProgressUpdate(function(res){
                //   console.log('上传进度', res.progress)
                //   console.log('已经上传的数据长度', res.totalBytesSent)
                //   console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
                  wx.showLoading({
                      title: `已上传${res.progress}%`,
                  })
              });
              
          },
      })
  },
  //更换背景
  bgi:function(){
      var that = this;
      wx.showActionSheet({
          itemList: ['相册', '拍照'],
          success: function (res) {
              if (res.tapIndex == 0) {
                  that.do_bgi('album');

              } else if (res.tapIndex == 1) {
                  that.do_bgi('camera');
              }
          }
      })
  },
  //执行背景更换程序
  do_bgi:function(type){
      var that = this;
      var is_login = common.checkLogin(false);
      if (!is_login) return;      
      wx.chooseImage({
          count: 1,
          sourceType: [type],
          success: function (res) {
              var tempPath = res.tempFilePaths[0];
              wx.saveFile({
                  tempFilePath: tempPath,
                  success:function(res){
                      var filePath = res.savedFilePath;
                      wx.setStorageSync('me_bgi', filePath);    //将个人中心背景图片的本地文件路径存在缓存中
                      common.toast('背景更换成功');
                  },
                  fail:function(){
                      common.toast('背景更换失败');
                  }
              })

          },
      })
  },
  //关闭弹层
  hidden_mask:function(){
      
      this.setData({
          showPopup: !this.data.showPopup,
          hidden_nickName:true,
          hidden_brief:true,
          hidden_password:true,
          hidden_phone: true,
          input_val:'',
      })
  },
  //显示修改昵称弹窗
  nickName:function(){      
      this.setData({
          showPopup: !this.data.showPopup,
          hidden_nickName:false,
      })            
  },
  //提交修改昵称
  submit_nickName:function(e){
        var flag = 1;
        var data=e.detail.value;        
        data.flag=flag;
        this.modify(data,flag);
        
  },
  //显示修改签名弹窗
  brief: function () {
      this.setData({
          showPopup: !this.data.showPopup,
          hidden_brief: false,
      })
  },
  //提交修改签名
  submit_brief: function (e) {      
      var data = e.detail.value;
      var that = this;
      var is_login = common.checkLogin(false);
      if (!is_login) return;
      var token = common.getToken();
      var userId = common.getUserId();
      var url = `${app.apiHost}centers/setuserbrief`;
      if (data) {
          data.userId = userId;
          data.token = token;
      }
      common.request(url, data, '', function () {          
          var userInfo = that.data.userInfo;
          userInfo.brief = data.brief;
          console.log(userInfo);
          that.setData({
              userInfo: userInfo,
              showPopup: !that.data.showPopup,
              hidden_nickName: true,
              hidden_brief: true,
              hidden_password: true,
              hidden_phone: true,
              input_val: '',
          })
      }, that);

  },
  //显示修改手机号弹窗
  phone: function () {
      this.setData({
          showPopup: !this.data.showPopup,
          hidden_phone: false,
      })
  },
  //提交修改手机号
  submit_phone: function (e) {
      var flag = 3;
      var data = e.detail.value;
      data.flag = flag;
      this.modify(data, flag);
  },
  //显示修改密码弹窗
  password: function () {
      this.setData({
          showPopup: !this.data.showPopup,
          hidden_password: false,
      })
  },
  //提交修改密码
  submit_password: function (e) {
      var flag = 4;
      var data = e.detail.value;
      data.flag = flag;
      this.modify(data, flag,'密码修改成功');
  },
  //修改性别
  sex:function(e){
       var sex=e.detail.value;
       
       if(this.data.userInfo.sex!=sex){     //修改了性别才进行更新,不修改不更新数据库
            this.modify({sex:sex,flag:2},2);
       }
  },
  //修改生日
  birthday:function(e){
        var birthdaytemp=e.detail.value;
        var birthday = birthdaytemp.replace(/-/g,'');
        if (this.data.userInfo.birthday != birthdaytemp) {     //修改了生日才进行更新,不修改不更新数据库
            this.modify({ birthday: birthday, flag: 10,birthdaytemp:birthdaytemp }, 10);
        }
  },
  //统一资料修改方法
  modify:function(data,flag,successmsg=''){
      var that = this;      
      var is_login = common.checkLogin(false);
      if (!is_login) return;
      var token = common.getToken();
      var userId = common.getUserId();
      var url = `${app.apiHost}centers/setting`;
      if(data){
          data.userId=userId;
          data.token=token;
      }
      common.request(url,data,'',function(){
          var index;
          switch (flag) {
              case 1:
                  index='nickName';
                  break;
              case 2:
                  index = 'sex';
                  break;
              case 3:
                  index = 'phone';
                  break;
              case 10:
                  index = 'birthday';
                  break;
              
              default:
                  index='';
          }
          
          var userInfo=that.data.userInfo;
          if (index) {
              if(flag==10){
                  userInfo.birthday=data.birthdaytemp;
                  
              }else{
                  userInfo[index] = data[index];
              }
              
          }
          
          
          that.setData({
              userInfo:userInfo,
              showPopup: false,
              hidden_nickName: true,
              hidden_brief: true,
              hidden_password: true,
              hidden_phone: true,
              input_val: '',
          })
      },that,successmsg);
  },
})